<template>
  <div class="container">
    <header class="header">
      <h1>评分系统管理界面</h1>
      <nav class="nav">
        <button class="nav-btn" :class="{ active: activeTab === 'contestants' }" @click="switchTab('contestants')">选手管理</button>
        <button class="nav-btn" :class="{ active: activeTab === 'judges' }" @click="switchTab('judges')">评委管理</button>
        <button class="nav-btn" :class="{ active: activeTab === 'scores' }" @click="switchTab('scores')">评分管理</button>
      </nav>
    </header>

    <main class="main-content">
      <section v-show="activeTab === 'contestants'" id="contestants" class="tab-content" :class="{ active: activeTab === 'contestants' }">
        <div class="section">
          <h2>添加选手</h2>
          <form class="form" @submit.prevent="addContestant">
            <div class="form-group">
              <label for="contestantNumber">选手编号：</label>
              <input id="contestantNumber" v-model.trim="contestantNumber" placeholder="请输入选手编号" required />
            </div>
            <div class="form-group">
              <label for="contestantName">选手姓名：</label>
              <input id="contestantName" v-model.trim="contestantName" placeholder="请输入选手姓名" required />
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary">添加选手</button>
            </div>
          </form>
        </div>

        <div class="section">
          <h2>选手列表</h2>
          <div class="contestant-controls">
            <button id="activateContestant" class="btn btn-secondary" :disabled="!selectedContestantId" @click="activateSelected">激活选中选手</button>
            <button id="deleteContestant" class="btn btn-danger" :disabled="!selectedContestantId" @click="deleteSelectedContestant">删除选中选手</button>
          </div>
          <div id="contestantsList" class="list-container">
            <div v-if="contestants.length === 0" class="loading">加载中...</div>
            <div v-else>
              <div v-for="c in contestants" :key="c.id" class="list-item" :class="{ active: c.is_active, selected: c.id === selectedContestantId }" @click="selectContestant(c.id)">
                <div class="list-item-info">
                  <strong>{{ c.number }} - {{ c.name }}</strong>
                  <div class="item-meta">
                    状态: <span class="status" :class="{ active: c.is_active, inactive: !c.is_active }">{{ c.is_active ? '当前激活' : '未激活' }}</span>
                  </div>
                </div>
                <div class="list-item-actions">
                  <button class="btn btn-secondary btn-activate" :disabled="c.is_active" @click.stop="activateContestant(c.id)">{{ c.is_active ? '已激活' : '激活' }}</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section v-show="activeTab === 'judges'" id="judges" class="tab-content" :class="{ active: activeTab === 'judges' }">
        <div class="section">
          <h2>添加评委</h2>
          <form class="form" @submit.prevent="addJudge">
            <div class="form-group">
              <label for="judgeName">评委姓名：</label>
              <input id="judgeName" v-model.trim="judgeName" placeholder="请输入评委姓名" required />
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary">添加评委</button>
            </div>
          </form>
        </div>

        <div class="section">
          <h2>评委列表</h2>
          <div class="judge-controls">
            <button id="deleteJudge" class="btn btn-danger" :disabled="!selectedJudgeId" @click="deleteSelectedJudge">删除选中评委</button>
          </div>
          <div id="judgesList" class="list-container">
            <div v-if="judges.length === 0">暂无评委数据</div>
            <div v-else>
              <div v-for="j in judges" :key="j.id" class="list-item" :class="{ selected: j.id === selectedJudgeId }" @click="selectJudge(j.id)">
                <div class="list-item-info">
                  <strong>{{ j.name }}</strong>
                  <div class="item-meta">创建时间: {{ new Date(j.created_at).toLocaleString() }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section v-show="activeTab === 'scores'" id="scores" class="tab-content" :class="{ active: activeTab === 'scores' }">
        <div class="section">
          <h2>评分管理</h2>
          <div class="score-controls">
            <select id="scoreContestantSelect" v-model.number="scoresContestantId">
              <option :value="0">选择选手查看评分</option>
              <option v-for="c in contestants" :key="c.id" :value="c.id">{{ c.number }} - {{ c.name }}</option>
            </select>
          </div>
          <div id="scoresManagement" class="scores-management">
            <p v-if="scores.length === 0 && scoresContestantId === 0" class="no-scores">请选择选手查看评分详情</p>
            <p v-else-if="scores.length === 0" class="no-scores">该选手暂无评分</p>
            <template v-else>
              <div class="scores-summary">
                <div class="summary-item"><div class="summary-label">评委数量</div><div class="summary-value">{{ scores.length }}</div></div>
                <div class="summary-item"><div class="summary-label">有效平均分</div><div class="summary-value">{{ averageScore.toFixed(1) }}</div></div>
                <div class="summary-item"><div class="summary-label">最高分</div><div class="summary-value">{{ maxScore.toFixed(1) }}</div></div>
                <div class="summary-item"><div class="summary-label">最低分</div><div class="summary-value">{{ minScore.toFixed(1) }}</div></div>
              </div>
              <table class="scores-table">
                <thead><tr><th>评委姓名</th><th>评分</th><th>评分时间</th><th>操作</th></tr></thead>
                <tbody>
                  <tr v-for="s in scores" :key="s.id">
                    <td class="judge-name">{{ s.judge_name }}</td>
                    <td class="score-value">{{ s.score.toFixed(1) }}</td>
                    <td>{{ new Date(s.created_at).toLocaleString() }}</td>
                    <td><button class="btn btn-danger btn-sm" @click="clearJudgeScoreByName(s.judge_name)">清空评分</button></td>
                  </tr>
                </tbody>
              </table>
            </template>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useScoringStore } from '@/stores/scoring'

const activeTab = ref<'contestants' | 'judges' | 'scores'>('contestants')
const scoringStore = useScoringStore()

// 监听标签页切换，立即刷新数据
async function switchTab(tab: 'contestants' | 'judges' | 'scores') {
  activeTab.value = tab
  // 切换标签页时立即刷新数据
  await scoringStore.initialize()
  // 如果切换到评分管理且有选中的选手，重新加载评分
  if (tab === 'scores' && scoresContestantId.value) {
    await scoringStore.loadScores(scoresContestantId.value)
  }
}

const contestantNumber = ref('')
const contestantName = ref('')
const selectedContestantId = ref<number | null>(null)

const judgeName = ref('')
const selectedJudgeId = ref<number | null>(null)

const scoresContestantId = ref<number>(0)

// 从 store 获取状态
const judges = computed(() => scoringStore.judges)
const contestants = computed(() => scoringStore.contestants)
const scores = computed(() => scoringStore.scores)
const averageScore = computed(() => scoringStore.averageScore)
const maxScore = computed(() => scoringStore.maxScore)
const minScore = computed(() => scoringStore.minScore)

function showToast(message: string, type: 'success' | 'error' | 'info' = 'info') {
  const el = document.createElement('div')
  el.className = `message ${type}`
  el.textContent = message
  el.style.cssText = 'position:fixed;top:20px;right:20px;z-index:1000;animation:slideIn .3s ease-out;'
  document.body.appendChild(el)
  setTimeout(() => el.remove(), 3000)
}

function selectContestant(id: number) { selectedContestantId.value = id }
function selectJudge(id: number) { selectedJudgeId.value = id }

async function addContestant() {
  if (!contestantNumber.value || !contestantName.value) { showToast('请填写完整的选手信息', 'error'); return }
  try {
    await scoringStore.createContestant({ number: contestantNumber.value, name: contestantName.value })
    contestantNumber.value = ''
    contestantName.value = ''
    showToast('选手添加成功', 'success')
  } catch (error) {
    showToast('选手添加失败', 'error')
  }
}

async function activateContestant(id: number) {
  try {
    await scoringStore.activateContestant(id)
    // 激活选手后立即清空评分数据，避免显示上一个选手的分数
    scoringStore.scores = []
    // 如果当前在评分管理页面，清空选中的选手
    if (activeTab.value === 'scores') {
      scoresContestantId.value = 0
    }
    showToast('选手激活成功', 'success')
  } catch (error) {
    showToast('选手激活失败', 'error')
  }
}

async function activateSelected() { if (selectedContestantId.value) await activateContestant(selectedContestantId.value) }

async function deleteSelectedContestant() {
  if (!selectedContestantId.value) return
  const c = contestants.value.find(c => c.id === selectedContestantId.value)
  if (!c) return
  if (!confirm(`确定要删除选手 "${c.number} - ${c.name}" 吗？\n删除后将同时删除该选手的所有评分记录！`)) return
  try {
    await scoringStore.deleteContestant(c.id)
    selectedContestantId.value = null
    showToast('选手删除成功', 'success')
  } catch (error) {
    showToast('选手删除失败', 'error')
  }
}

async function addJudge() {
  if (!judgeName.value) { showToast('请输入评委姓名', 'error'); return }
  try {
    await scoringStore.createJudge({ name: judgeName.value })
    judgeName.value = ''
    showToast('评委添加成功', 'success')
  } catch (error) {
    showToast('评委添加失败', 'error')
  }
}

async function deleteSelectedJudge() {
  if (!selectedJudgeId.value) return
  const j = judges.value.find(j => j.id === selectedJudgeId.value)
  if (!j) return
  if (!confirm(`确定要删除评委 "${j.name}" 吗？\n删除后将同时删除该评委的所有评分记录！`)) return
  try {
    await scoringStore.deleteJudge(j.id)
    selectedJudgeId.value = null
    showToast('评委删除成功', 'success')
  } catch (error) {
    showToast('评委删除失败', 'error')
  }
}

async function clearJudgeScoreByName(judgeName: string) {
  if (!scoresContestantId.value) return
  if (!confirm(`确定要清空评委 ${judgeName} 的评分吗？`)) return
  try {
    await scoringStore.clearJudgeScore(judgeName, scoresContestantId.value)
    showToast('评分清空成功', 'success')
  } catch (error) {
    showToast('评分清空失败', 'error')
  }
}

watch(scoresContestantId, async (id) => {
  if (id) await scoringStore.loadScores(id)
})

let refreshInterval: number | undefined

onMounted(async () => {
  await scoringStore.initialize()
  // 每10秒自动刷新数据（减少刷新频率）
  refreshInterval = setInterval(async () => {
    await scoringStore.initialize()
    // 如果当前在评分管理页面且有选中的选手，重新加载评分
    if (activeTab.value === 'scores' && scoresContestantId.value) {
      await scoringStore.loadScores(scoresContestantId.value)
    }
  }, 10000)
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>
